package com.bw.cashier.page

import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import android.widget.Toast
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.path.RouterPath
import com.bw.cashier.R
import com.bw.cashier.adapter.BillAdapter
import com.bw.cashier.adapter.BillChargeAdapter
import com.bw.cashier.databinding.ActivityBillBinding
import com.bw.cashier.entity.ChargeDataEntityItem
import com.bw.cashier.vm.CashierViewModel
import com.bw.common.event.CustomEvent
import com.bw.common.view.BaseMvvmActivity
import com.google.zxing.integration.android.IntentIntegrator
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 账单详情页面
 */
@Route(path = RouterPath.PATH_CASHIER_DETAIL_PATH)
@AndroidEntryPoint
class BillDetailActivity : BaseMvvmActivity<ActivityBillBinding>() {
    @JvmField
    @Autowired
    var idc :Int = 0
    private val mViewModel :CashierViewModel by viewModels()
//    private val mAdapter = BillChargeAdapter()
    private val bAdapter = BillAdapter()
    override fun getLayoutId(): Int = R.layout.activity_bill
    var address=""
    var name=""
    var price = ""
    var id = ""
    var index:Int =0
    var checkedAll :Boolean = false

    //单价
    var sumPrice = 0
    var sumCount = 0
    override fun initViews() {
        super.initViews()
        ARouter.getInstance().inject(this)

        mDataBinding.back.setOnClickListener { finish() }
        //详情数据
        mViewModel.mBillSuccess.observe(this){
            address = it.chargeType
            price = it.chargeAmount.toString()
            id = it.id.toString()
            name = it.payerName
            mDataBinding.cashierDetailName.setText(it.chargeType)
            mDataBinding.cashierDetailUsername.setText("户主：${name}")
            mDataBinding.cashierDetailPhone.setText("联系电话：${it.contactNumber}")
            mDataBinding.cashierDetailPrice.setText("￥${price}")
        }

        //收费列表
        mDataBinding.cashierDetailRv.adapter = bAdapter
        mViewModel.mChargeSuccess.observe(this){
            bAdapter.data.clear()
            bAdapter.data.addAll(it)
            bAdapter.notifyDataSetChanged()
        }
        //单选
        bAdapter.addChildClickViewIds(R.id.checked)
        bAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.checked ->{
                    //点击事件
                    bAdapter.data[position].isChecked = !bAdapter.data[position].isChecked
                    index = position
                }
            }
            checkPrice()
        }
        mDataBinding.allChecked.setOnClickListener{
          //  mDataBinding.allChecked.isChecked = !mDataBinding.allChecked.isChecked
            bAdapter.data.forEach {
                it.isChecked = mDataBinding.allChecked.isChecked
            }
            bAdapter.notifyDataSetChanged()
            checkPrice()
        }



        //点击添加账单
        mDataBinding.addBill.setOnClickListener {
            ARouter.getInstance().build(RouterPath.PATH_ADD_CHARGE_PATH).navigation()
        }
        //点击收款
        bAdapter.addChildClickViewIds(R.id.checked_money)
        mDataBinding.charge.setOnClickListener {
            val payType = arrayOf("扫码收款" , "二维码收款" , "现金收款")
            val pvOption = OptionsPickerBuilder(this){p1,_,_,_ ->
                if (payType[p1] == "扫码收款"){
                    startScan()
                }else if (payType[p1] == "二维码收款"){
                    ARouter.getInstance().build(RouterPath.PATH_CODE_CHARGE_PATH)
                        .withString("address",address)
                        .withString("name",name)
                        .withString("price",price)
                        .withString("id",id)
                        .navigation()
                }else if (payType[p1] == "现金收款"){
                    ToastUtils.showLong("已记账")
                }
            }.setSubmitText("确定")
                .setTitleText("选择收款方式")
                .setCancelText("取消")
                .build<String>()

            pvOption.setPicker(payType.toList())

            pvOption.show()
        }
    }

    //单选计算价格
    fun checkPrice(){

        sumPrice = 0
        sumCount = 0
        bAdapter.data.forEach {
            if (it.isChecked){
                sumPrice += it.actualAmount
                sumCount += 1
            }
        }

        mDataBinding.checkedMoney.text = "合计：￥${sumPrice}"

        //计算一下是否选择
        var list = mutableListOf<Boolean>()
        bAdapter.data.forEach{
            list.add(it.isChecked)
        }
        if (false in list){
            mDataBinding.allChecked.isChecked = false
        }else{
            mDataBinding.allChecked.isChecked = true
        }


    }

//    fun checkPrice(res: List<ChargeDataEntityItem>): Int {
//        return res.filter { it.isChecked }
//            .sumOf { it.actualAmount }
//
//    }
    //动态请求权限
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 100 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startScan()
        } else {
            Toast.makeText(this, "需要相机权限才能扫码", Toast.LENGTH_SHORT).show()
        }
    }
    //检查相机权限
    private fun startScan() {
        val integrator = IntentIntegrator(this)
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE) // 只扫描二维码
        integrator.setPrompt("请将二维码对准扫描框") // 提示文字
        integrator.setCameraId(0) // 默认后置摄像头
        integrator.setBeepEnabled(true) // 扫描成功播放声音
        integrator.setBarcodeImageEnabled(true) // 保留扫描图片
        integrator.initiateScan() // 启动扫描
    }
    //处理扫描结果
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents ==  null) {
                Toast.makeText(this, "取消扫描", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "扫描结果: ${result.contents}", Toast.LENGTH_SHORT).show()

            }
        }
    }



    override fun loadData() {
        super.loadData()
        mViewModel.getBillData(idc)
        mViewModel.getChargeData(879)
    }


        @Subscribe(threadMode = ThreadMode.MAIN)
        fun onCusEventBus(event: CustomEvent){
            if (event.target == RouterPath.PATH_CASHIER_DETAIL_PATH){
                when(event.type){
                    1->{
                        mViewModel.getChargeData(879)
                    }
                }
            }
        }

}